const path = require('path');
const webpack = require('webpack');
const uglify = require('uglifyjs-webpack-plugin');
const htmlWebpackPlugin = require('html-webpack-plugin');
const extractTextPlugin = require('extract-text-webpack-plugin');

/**
 * 获取当期所依赖模块的版本号
 */
function getModulesVersion() {
	let mvs = {};
	let regexp = /^npm_package_.{0,3}dependencies_/gi;
	for (let m in process.env) {
		if (regexp.test(m)) {
			mvs[m.replace(regexp, '').replace(/_/g, '-')] = process.env[m].replace(/(~|\^)/g, '');
		}
	}
	return mvs;
}

// cdn配置
var externals = {};
var dependencieModules = getModulesVersion();
var externalModules = [
	{ name: 'vue', scope: 'Vue', js: 'vue.min.js' },
	{ name: 'element-ui', scope: 'ELEMENT', js: 'index.js', css: 'theme-chalk/index.css' },
];
externalModules.forEach(item => {
	let cdn = 'https://cdn.bootcss.com';
	if (item.name in dependencieModules) {
		let version = dependencieModules[item.name];
		item.css = item.css && [cdn, item.name, version, item.css].join('/');
		item.js = item.js && [cdn, item.name, version, item.js].join('/');
		externals[item.name] = item.scope;
	} else {
		throw new Error('cdn模块配置找不到');
	}
});

module.exports = {
	entry: ['./src/main.js'],
	externals: externals, //构建时忽略的模块
	output: {
		path: path.resolve(__dirname, '../dist'),
		filename: 'scripts/app.[hash].js',
	},
	resolve: {
		alias: {
			vue: 'vue/dist/vue.js', //使用别名
		},
	},
	plugins: [
		new webpack.HotModuleReplacementPlugin(),
		new htmlWebpackPlugin({
			template: './index.html', //生成的新的html文件所依赖的模板
			filename: 'index.html', //生成的新的html文件的名字
			title: 'html-webpck-plugin', //页面中通过htmlWebpackPlugin.options.title可以取到值
			cdns: externalModules, //cdn配置
			minify: {
				caseSensitive: false, //是否大小写敏感
				collapseBooleanAttributes: true, //是否简写boolean格式的属性如：disabled="disabled" 简写为disabled
				collapseWhitespace: true, //是否去除空格
				removeComments: true, //是否去除注释
				removeEmptyAttributes: true, //是否去除空属性
			},
		}),
		// new uglify(), //压缩js 【因为es6的问题，导致压缩异常，暂时屏蔽该代码】
		new extractTextPlugin('styles/[name].[hash].css'), //单独打包css; 当前最新版本为3.0.2，暂不支持webpack4.x，需要使用4.0 beta，即extract-text-webpack-plugin@next
	],
	module: {
		rules: [
			{
				test: /\.css$/, //匹配css文件
				use: extractTextPlugin.extract({
					//抽离css
					fallback: 'style-loader',
					use: 'css-loader',
				}),
			},
		],
	},
};
